package com.stress.testing.instrumentation;

import com.stress.testing.common.AgentContext;
import com.stress.testing.common.ClassFileTransformerRegistry;
import com.stress.testing.common.plugin.DefaultPluginLoader;
import com.stress.testing.common.plugin.PluginContext;
import com.stress.testing.common.plugin.PluginLoader;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import java.util.List;

public class ByteBuddyClassFileTransformerRegistry implements ClassFileTransformerRegistry {

    @Override
    public void register(AgentContext context) {
        PluginLoader pluginLoader = new DefaultPluginLoader();
        List<PluginContext> pluginContexts = pluginLoader.load(context);

        AgentBuilder agentBuilder = new AgentBuilder.Default();
        for (PluginContext pluginContext : pluginContexts) {
            SimpleTransformer transformer = new SimpleTransformer(pluginContext);
            ElementMatcher<TypeDescription> elementMatcher =
                    new SimpleTypeElementMatcher(pluginContext.getPlugin().getClassMatcher());

            agentBuilder = agentBuilder.type(elementMatcher).transform(transformer);
        }

        agentBuilder.installOn(context.getInstrumentation());
    }
}
